/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webaccess.retailws.Action;

import com.webaccess.retailws.Bean.BrandBean;
import com.webaccess.retailws.Bean.ProductBean;
import com.webaccess.retailws.Bean.CategoryBean;
import com.webaccess.retailws.Bean.UserAddressBean;
import com.webaccess.retailws.Delegate.CategoryDelegate;
import com.webaccess.retailws.Delegate.ProductDelegate;
import com.webaccess.retailws.Delegate.BrandDelegate;
import com.webaccess.retailws.Delegate.UserInfoDelegate;
import com.webaccess.retailws.Util.CategoryUtil;
import com.webaccess.retailws.Util.CommonUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.upload.FormFile;
import com.webaccess.retailws.Util.ProductUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;

/**
 *
 * @author Owner
 */
public class ProductDispatchAction extends DispatchAction {

    private String SUCCESS = "success";
    ActionMessages errors = null;
    CategoryUtil categUtil = new CategoryUtil();
    CommonUtil commUtil = new CommonUtil();
    CategoryDelegate categDelegate = new CategoryDelegate();
    BrandDelegate brandDelegateObj = new BrandDelegate();
    ProductUtil prodUtil = null;
    ProductDelegate prodDelegate = null;
    UserInfoDelegate userDelegate = null;
    ProductBean prodBean = null;
    CategoryBean categBean = null;
    BrandBean brandBeanObj = null;
    UserAddressBean userAddrBean = null;

    public ActionForward getProductByCategory(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        LinkedHashMap productLHMap = new LinkedHashMap();
        prodDelegate = new ProductDelegate();
        Long categoryId = 0L;
        try {

            categoryId = Long.parseLong(String.valueOf(request.getParameter("categoryId")));

            productLHMap = prodDelegate.getProductByCategoryLHMap(categoryId);

            Set productSet = productLHMap.entrySet();
            Iterator i = productSet.iterator();
            PrintWriter out = response.getWriter();

            out.println("<select name='dealProductId' id='product' onchange='javascript:return getProductDetail('./deal.do?action=getProductDetails','DealBean');'>");
            out.println("<option value='0'>--Select Product--</option>");

            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                out.println("<option value='" + me.getKey() + "'>" + me.getValue() + "</option>");
            }
            out.println("</select>");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return null;
        }
    }

    public ActionForward advancedSearch(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        categBean = new CategoryBean();
        brandBeanObj = new BrandBean();
        errors = new ActionMessages();
        ProductBean[] prodBeanList = null;
        int searchCriteria = 0;
        String productName = "", product = "", minPrice = "", maxPrice = "";
        Long productCategoryId = 0L, productBrandId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("brandMap", brandDelegateObj.getBrandLHMap());
            request.setAttribute("mainCategoryMap", categDelegate.getCategoryLHMap(0));
            searchCriteria = Integer.parseInt(request.getParameter("searchCriteria"));
            productName = String.valueOf(request.getParameter("productName"));
            product = String.valueOf(request.getParameter("product"));
            minPrice = String.valueOf(request.getParameter("minPrice"));
            maxPrice = String.valueOf(request.getParameter("maxPrice"));
            productBrandId = Long.parseLong(String.valueOf(request.getParameter("productBrandId")));
            productCategoryId = Long.parseLong(String.valueOf(request.getParameter("productCategoryId")));

            Pattern numericExp = Pattern.compile("/^[0-9]+$/");
            Matcher matchMinPrice = numericExp.matcher(minPrice.toString());
            Matcher matchMaxPrice = numericExp.matcher(maxPrice.toString());

            if (searchCriteria == 1 && product.equalsIgnoreCase("")) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchkeyword.required"));
            } else if (searchCriteria == 2 && productName.equalsIgnoreCase("All")) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchcharacter.required"));
            } else if (searchCriteria == 3 && productBrandId < 0) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchbrand.required"));
            } else if (searchCriteria == 4 && productCategoryId < 0) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchcategory.required"));
            } else if (searchCriteria == 5 && minPrice.equalsIgnoreCase("") && maxPrice.equalsIgnoreCase("")) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchprice.required"));
            } else if (searchCriteria == 5 && matchMinPrice.find() && matchMaxPrice.find()) {
                errors.add("errAdvancedSearch", new ActionMessage("errors.advsearchprice.invalid"));
            } else {
                if (searchCriteria == 1) {
                    request.setAttribute("searchCriteria", "Keyword");
                    request.setAttribute("searchValue", product);
                    prodBeanList = prodDelegate.searchProductByPhrase(product);
                    request.setAttribute("productList", prodBeanList);
                } else if (searchCriteria == 2) {
                    request.setAttribute("searchCriteria", "Character");
                    request.setAttribute("searchValue", productName);
                    prodBeanList = prodDelegate.searchProductByName(productName);
                    request.setAttribute("productList", prodBeanList);
                } else if (searchCriteria == 3) {
                    request.setAttribute("searchCriteria", "Brand");
                    brandBeanObj = brandDelegateObj.getBrand(productBrandId);
                    request.setAttribute("searchValue", brandBeanObj.getBrandName());
                    prodBeanList = prodDelegate.searchProductByBrand(productBrandId);
                    request.setAttribute("productList", prodBeanList);
                } else if (searchCriteria == 4) {
                    request.setAttribute("searchCriteria", "Category");
                    categBean = categDelegate.getCategory(productCategoryId);
                    request.setAttribute("searchValue", categBean.getCategoryName());
                    prodBeanList = prodDelegate.getProductByCategory(productCategoryId);
                    request.setAttribute("productList", prodBeanList);
                } else if (searchCriteria == 5) {
                    request.setAttribute("searchCriteria", "Price");
                    String price = "min :" + minPrice + "max :" + maxPrice;
                    request.setAttribute("searchValue", price);
                    prodBeanList = prodDelegate.getProductByPrice(Long.parseLong(minPrice), Long.parseLong(maxPrice));
                    request.setAttribute("productList", prodBeanList);
                }
            }
            saveErrors(request, errors);
            if (errors.isEmpty()) {
                SUCCESS = "searchpageshow";
            } else {
                SUCCESS = "searchpagefailure";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProducts(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        categDelegate = new CategoryDelegate();
        prodBean = new ProductBean();
        categBean = new CategoryBean();
        Long categoryId = 0L;
        String searchProduct = "";
        try {
            commUtil.getTopRightListMap(request);

            categoryId = Long.parseLong(request.getParameter("category"));
            searchProduct = request.getParameter("searchProduct").toString();
            if (categoryId == 0 && searchProduct.equalsIgnoreCase("")) {
                request.setAttribute("CategoryList", categDelegate.getMainCategoryList());
                SUCCESS = "showonlinestore";
            } else if (categoryId > 0 && searchProduct.equalsIgnoreCase("")) {
                categBean = categDelegate.getCategory(categoryId);//String.valueOf(request.getParameter("categoryName"));
                String categoryName = categBean.getCategoryName();
                request.setAttribute("categoryName", categoryName);
                CategoryBean[] subCategoryList = categDelegate.getSubCategories(categoryId);
                request.setAttribute("subCategoryList", subCategoryList);
                ProductBean[] prodBeanList = prodDelegate.getProductByCategory(categoryId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "productbycategoryshow";
            } else {
                categBean = categDelegate.getCategory(categoryId);//String.valueOf(request.getParameter("categoryName"));
                String categoryName = categBean.getCategoryName();
                request.setAttribute("categoryName", categoryName);
                request.setAttribute("searchKeyword", searchProduct);
                ProductBean[] prodBeanList = prodDelegate.getSearchProducts(categoryId, searchProduct);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "searchproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward updateProduct(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        prodDelegate = new ProductDelegate();
        prodUtil = new ProductUtil();
        errors = new ActionMessages();

        String productName = "", productTitle = "", productDescription = "", filePath = "", productSmallImageName = "", productLargeImageName = "", productPrice = "", productTaxValue = "", productDiscount = "", productQty = "";
        Long productBrandId = 0L, productCategoryId = 0L, productStatusId = 0L, productId = 0L;
        int productTaxable = 0;

        try {
            commUtil.getTopRightListMap(request);
            DynaActionForm prodDynaForm = (DynaActionForm) form;
            if (isTokenValid(request)) {
                productId = Long.parseLong(request.getParameter("productId"));
                productName = String.valueOf(prodDynaForm.getString("productName"));
                productTitle = String.valueOf(prodDynaForm.get("productTitle"));
                productDescription = String.valueOf(prodDynaForm.get("productDescription"));
                FormFile productSmallImage = (FormFile) prodDynaForm.get("productSmallImage");
                FormFile productLargeImage = (FormFile) prodDynaForm.get("productLargeImage");
                productPrice = String.valueOf(prodDynaForm.get("productPrice"));
                productDiscount = String.valueOf(prodDynaForm.get("productDiscount"));
                productQty = String.valueOf(prodDynaForm.get("productQty"));
                productBrandId = Long.parseLong(request.getParameter("productBrandId"));
                productCategoryId = Long.parseLong(request.getParameter("productCategoryId"));
                productStatusId = Long.parseLong(request.getParameter("productStatusId"));
                productTaxValue = String.valueOf(prodDynaForm.get("productTaxValue"));
                productSmallImageName = String.valueOf(prodDynaForm.getString("productSmallImageName"));
                productLargeImageName = String.valueOf(prodDynaForm.getString("productLargeImageName"));
                if ((Boolean) prodDynaForm.get("productTaxable") == true) {
                    productTaxable = 1;
                }
                Pattern numericExp = Pattern.compile("/^[0-9]+$/");
                Pattern fileType = Pattern.compile("/.*\\.(gif)|(jpeg)|(jpg)|(png)$/");
                Matcher matchProductPrice = numericExp.matcher(productPrice.toString());
                Matcher matchProductDiscount = numericExp.matcher(productDiscount.toString());
                Matcher matchProductQty = numericExp.matcher(productQty.toString());
                Matcher matchTaxValue = numericExp.matcher(productTaxValue.toString());
                Matcher matchPSIFileType = fileType.matcher(productSmallImage.getContentType());
                Matcher matchPLIFileType = fileType.matcher(productLargeImage.getContentType());

                if (productName.equalsIgnoreCase("") || productTitle.equalsIgnoreCase("") || productDescription.equalsIgnoreCase("") || productPrice.equalsIgnoreCase("") || productDiscount.equalsIgnoreCase("")
                        || productQty.equalsIgnoreCase("") || productBrandId == 0 || productCategoryId == 0 || productStatusId == 0) {
                    errors.add("errProduct", new ActionMessage("errors.product.required"));
                } else if (matchProductPrice.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productprice.invalid"));
                } else if (Integer.parseInt(productPrice) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productprice.valid"));
                } else if (matchProductDiscount.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productdiscount.invalid"));
                } else if (Integer.parseInt(productDiscount) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productdiscount.valid"));
                } else if (matchProductQty.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productqty.invalid"));
                } else if (Integer.parseInt(productQty) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productqty.valid"));
                } else if ((Boolean) prodDynaForm.get("productTaxable") == true) {
                    if (productTaxValue.equalsIgnoreCase("")) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.required"));
                    } else if (matchTaxValue.find()) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.invalid"));
                    } else if (Integer.parseInt(productTaxValue) <= 0) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.valid"));
                    }
                } else if (productSmallImage.getFileSize() != 0 || productLargeImage.getFileSize() != 0) {
                    if (!matchPSIFileType.find()) {
                        errors.add("errProductSmallImage", new ActionMessage("errors.productimage.filetype"));
                    } else if (productSmallImage.getFileSize() > 1048576) { //1MB
                        errors.add("errProductSmallImage", new ActionMessage("errors.productimage.size"));
                    } else if (!matchPLIFileType.find()) {
                        errors.add("errProductLargeImage", new ActionMessage("errors.productimage.filetype"));
                    } else if (productLargeImage.getFileSize() > 1048576) { //1MB (524288 = 0.5MB = 512KB)
                        errors.add("errProductLargeImage", new ActionMessage("errors.productimage.size"));
                    } else {
                        filePath = getServlet().getServletContext().getRealPath("/") + "products";
                        productSmallImageName = prodUtil.uploadFile(productSmallImage, filePath);
                        productLargeImageName = prodUtil.uploadFile(productLargeImage, filePath);
                        SUCCESS = prodUtil.saveProduct(productId, productName, productTitle, productDescription, productDiscount, productPrice, productBrandId, productCategoryId,
                                productSmallImageName, productLargeImageName, productStatusId, productQty, productTaxValue, productTaxable);
                    }
                } else {
                    SUCCESS = prodUtil.saveProduct(productId, productName, productTitle, productDescription, productDiscount, productPrice, productBrandId, productCategoryId,
                            productSmallImageName, productLargeImageName, productStatusId, productQty, productTaxValue, productTaxable);
                }
                resetToken(request);
                saveErrors(request, errors);
                if (errors.isEmpty()) {
                    SUCCESS = "productsuccess";
                } else {
                    SUCCESS = "updateproductfailure";
                }
            }
            saveToken(request);
        } catch (Exception ex) {
            SUCCESS = "updateproductfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward saveProduct(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        prodDelegate = new ProductDelegate();
        prodUtil = new ProductUtil();
        errors = new ActionMessages();

        String productName = "", productTitle = "", productDescription = "", filePath = "", productSmallImageName = "", productLargeImageName = "", productPrice = "", productTaxValue = "", productDiscount = "", productQty = "";
        Long productBrandId = 0L, productCategoryId = 0L, productStatusId = 0L;
        int productTaxable = 0;
        try {
            commUtil.getTopRightListMap(request);
            DynaActionForm prodDynaForm = (DynaActionForm) form;
            if (isTokenValid(request)) {
                productName = String.valueOf(prodDynaForm.getString("productName"));
                productTitle = String.valueOf(prodDynaForm.get("productTitle"));
                productDescription = String.valueOf(prodDynaForm.get("productDescription"));
                FormFile productSmallImage = (FormFile) prodDynaForm.get("productSmallImage");
                FormFile productLargeImage = (FormFile) prodDynaForm.get("productLargeImage");
                productPrice = String.valueOf(prodDynaForm.get("productPrice"));
                productDiscount = String.valueOf(prodDynaForm.get("productDiscount"));
                productQty = String.valueOf(prodDynaForm.get("productQty"));
                productBrandId = Long.parseLong(request.getParameter("productBrandId"));
                productCategoryId = Long.parseLong(request.getParameter("productCategoryId"));
                productStatusId = Long.parseLong(request.getParameter("productStatusId"));
                productTaxValue = String.valueOf(prodDynaForm.get("productTaxValue"));
                if ((Boolean) prodDynaForm.get("productTaxable") == true) {
                    productTaxable = 1;
                }
                Pattern numericExp = Pattern.compile("/^[0-9]+$/");
                Pattern fileType = Pattern.compile("/.*\\.(gif)|(jpeg)|(jpg)|(png)$/");
                Matcher matchProductPrice = numericExp.matcher(productPrice.toString());
                Matcher matchProductDiscount = numericExp.matcher(productDiscount.toString());
                Matcher matchProductQty = numericExp.matcher(productQty.toString());
                Matcher matchTaxValue = numericExp.matcher(productTaxValue.toString());
                Matcher matchPSIFileType = fileType.matcher(productSmallImage.getContentType());
                Matcher matchPLIFileType = fileType.matcher(productLargeImage.getContentType());

                if (productName.equalsIgnoreCase("") || productTitle.equalsIgnoreCase("") || productDescription.equalsIgnoreCase("") || productPrice.equalsIgnoreCase("") || productDiscount.equalsIgnoreCase("")
                        || productQty.equalsIgnoreCase("") || productBrandId == 0 || productCategoryId == 0 || productStatusId == 0) {
                    errors.add("errProduct", new ActionMessage("errors.product.required"));
                } else if (matchProductPrice.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productprice.invalid"));
                } else if (Long.parseLong(productPrice) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productprice.valid"));
                } else if (matchProductDiscount.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productdiscount.invalid"));
                } else if (Long.parseLong(productDiscount) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productdiscount.valid"));
                } else if (matchProductQty.find()) {
                    errors.add("errProduct", new ActionMessage("errors.productqty.invalid"));
                } else if (Long.parseLong(productQty) <= 0) {
                    errors.add("errProduct", new ActionMessage("errors.productqty.valid"));
                } else if ((Boolean) prodDynaForm.get("productTaxable") == true) {
                    if (productTaxValue.equalsIgnoreCase("")) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.required"));
                    } else if (matchTaxValue.find()) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.invalid"));
                    } else if (Long.parseLong(productTaxValue) <= 0) {
                        errors.add("errProduct", new ActionMessage("errors.producttax.valid"));
                    }
                } else if (productSmallImage.getFileSize() != 0 || productLargeImage.getFileSize() != 0) {
                    if (!matchPSIFileType.find()) {
                        errors.add("errProductSmallImage", new ActionMessage("errors.productimage.filetype"));
                    } else if (productSmallImage.getFileSize() > 1048576) { //1MB
                        errors.add("errProductSmallImage", new ActionMessage("errors.productimage.size"));
                    } else if (! !matchPLIFileType.find()) {
                        errors.add("errProductLargeImage", new ActionMessage("errors.productimage.filetype"));
                    } else if (productLargeImage.getFileSize() > 1048576) { //1MB (524288 = 0.5MB = 512KB)
                        errors.add("errProductLargeImage", new ActionMessage("errors.productimage.size"));
                    } else {
                        filePath = getServlet().getServletContext().getRealPath("/") + "products";
                        productSmallImageName = prodUtil.uploadFile(productSmallImage, filePath);
                        productLargeImageName = prodUtil.uploadFile(productLargeImage, filePath);
                        SUCCESS = prodUtil.saveProduct(null, productName, productTitle, productDescription, productDiscount, productPrice, productBrandId, productCategoryId,
                                productSmallImageName, productLargeImageName, productStatusId, productQty, productTaxValue, productTaxable);
                    }
                } else {

                    productSmallImageName = "no_image.gif";
                    productLargeImageName = "ImageNotFound.jpg";

                    SUCCESS = prodUtil.saveProduct(null, productName, productTitle, productDescription, productDiscount, productPrice, productBrandId, productCategoryId,
                            productSmallImageName, productLargeImageName, productStatusId, productQty, productTaxValue, productTaxable);
                }
                resetToken(request);
                saveErrors(request, errors);
                if (errors.isEmpty()) {
                    SUCCESS = "productsuccess";
                } else {
                    SUCCESS = "saveproductfailure";
                }
            }
            saveToken(request);
        } catch (Exception ex) {
            SUCCESS = "saveproductfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showAllProducts(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        commUtil.getTopRightListMap(request);

        SUCCESS = "showproductlist";
        return mapping.findForward(SUCCESS);
    }

    public ActionForward showAddProduct(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());
            saveToken(request);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "addproductshow";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showEditProduct(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodBean = new ProductBean();
        prodDelegate = new ProductDelegate();
        Long productId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());
            productId = Long.parseLong(request.getParameter("productid"));
            prodBean = prodDelegate.getProduct(productId);
            request.setAttribute("product", prodBean);
            saveToken(request);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "editproductshow";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showManageProducts(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());

            ProductBean[] prodBeanList = prodDelegate.getAllProducts();
            request.setAttribute("productList", prodBeanList);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "manageproductshow";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward deleteProduct(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        Long productId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            productId = Long.parseLong(request.getParameter("productId"));

            boolean isProductDeleted = prodDelegate.deleteProduct(productId);
            if (isProductDeleted == true) {
                SUCCESS = "productsuccess";
            } else {
                SUCCESS = "deleteproductfailure";
            }
        } catch (Exception ex) {
            SUCCESS = "deleteproductfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProductByPhrase(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        String product = "";
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());
            product = request.getParameter("product");
            if (product.equalsIgnoreCase("")) {
                SUCCESS = "productsuccess";
            } else {
                ProductBean[] prodBeanList = prodDelegate.searchProductByPhrase(product);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "manageproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProductByName(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        String productName = "";
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());

            productName = request.getParameter("productName");
            if (productName.equalsIgnoreCase("All")) {
                SUCCESS = "productsuccess";
            } else {
                ProductBean[] prodBeanList = prodDelegate.searchProductByName(productName);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "manageproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProductByStatus(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        Long productStatusId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());

            productStatusId = Long.parseLong(request.getParameter("productStatusId"));

            if (productStatusId == 0) {
                SUCCESS = "productsuccess";
            } else {
                ProductBean[] prodBeanList = prodDelegate.searchProductByStatus(productStatusId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "manageproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProductByCategory(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        Long productCategoryId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());
            productCategoryId = Long.parseLong(request.getParameter("productCategoryId"));
            if (productCategoryId == 0) {
                SUCCESS = "productsuccess";
            } else {
                ProductBean[] prodBeanList = prodDelegate.searchProductByCategory(productCategoryId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "manageproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchProductByBrand(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        Long productBrandId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("brandList", brandDelegateObj.getBrandLHMap());
            request.setAttribute("parentCategList", categDelegate.getSubCategoryLHMap());
            productBrandId = Long.parseLong(request.getParameter("productBrandId"));
            if (productBrandId == 0) {
                SUCCESS = "productsuccess";
            } else {
                ProductBean[] prodBeanList = prodDelegate.searchProductByBrand(productBrandId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "manageproductshow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showProductByCategory(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        categBean = new CategoryBean();

        try {
            commUtil.getTopRightListMap(request);
            Long categoryId = Long.parseLong(String.valueOf(request.getParameter("categoryId")));
            categBean = categDelegate.getCategory(categoryId);//String.valueOf(request.getParameter("categoryName"));
            String categoryName = categBean.getCategoryName();
            request.setAttribute("categoryName", categoryName);
            CategoryBean[] subCategoryList = categDelegate.getSubCategories(categoryId);
            request.setAttribute("subCategoryList", subCategoryList);
            ProductBean[] prodBeanList = prodDelegate.getProductByCategory(categoryId);
            request.setAttribute("productList", prodBeanList);
            SUCCESS = "productbycategoryshow";

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showProductBySubCategory(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        categBean = new CategoryBean();

        try {
            commUtil.getTopRightListMap(request);
            Long subCategoryId = Long.parseLong(String.valueOf(request.getParameter("categoryId")));
            categBean = categDelegate.getCategory(subCategoryId);//String.valueOf(request.getParameter("categoryName"));
            String subCategoryName = categBean.getCategoryName();
            request.setAttribute("subCategoryName", subCategoryName);
            CategoryBean[] subCategoryList = categDelegate.getSubCategories(subCategoryId);
            if (subCategoryList != null) {
                request.setAttribute("subCategoryList", subCategoryList);
                ProductBean[] prodBeanList = prodDelegate.getProductBySubCategory(subCategoryId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "productbycategoryshow";
            } else {
                ProductBean[] prodBeanList = prodDelegate.getProductBySubCategory(subCategoryId);
                request.setAttribute("productList", prodBeanList);
                SUCCESS = "productbysubcategoryshow";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showProductByPrice(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();

        try {
            commUtil.getTopRightListMap(request);
            Long min = Long.parseLong(String.valueOf(request.getParameter("min")));
            Long max = Long.parseLong(String.valueOf(request.getParameter("max")));

            ProductBean[] prodBeanList = prodDelegate.getProductByPrice(min, max);
            request.setAttribute("productList", prodBeanList);
            SUCCESS = "productbypriceshow";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showProductByBrand(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();

        try {
            commUtil.getTopRightListMap(request);
            Long brandId = Long.parseLong(String.valueOf(request.getParameter("brandId")));
            String brandName = String.valueOf(request.getParameter("brandName"));
            request.setAttribute("brandName", brandName);
            ProductBean[] prodBeanList = prodDelegate.getProductByBrand(brandId);
            request.setAttribute("productList", prodBeanList);
            SUCCESS = "productbybrandshow";

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showProductDetails(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();

        try {
            commUtil.getTopRightListMap(request);
            Long productId = Long.parseLong(request.getParameter("productId"));
            prodBean = prodDelegate.getProduct(productId);
            request.setAttribute("productName", prodBean.getProductName());
            request.setAttribute("productDetails", prodBean);
            SUCCESS = "productdetailshow";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward addToCart(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        errors = new ActionErrors();
        prodUtil = new ProductUtil();
        commUtil = new CommonUtil();
        HttpSession loginSession = request.getSession(true);
        Long cartId = 0L, cartProductId = 0L, productPrice = 0L, cartCost = 0L, cartProductCost = 0L, cartTotal = 0L;
        String addToCartQty = "";
        boolean isProductExist = false;
        int temp = 0;
        try {
            commUtil.getTopRightListMap(request);
            int direct = Integer.parseInt(request.getParameter("direct"));
            if (direct == 0) {
                DynaActionForm addToCartDynaForm = (DynaActionForm) form;
                addToCartQty = String.valueOf(addToCartDynaForm.get("addToCartQty"));
            } else {
                addToCartQty = "1";
            }
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            Long productId = Long.parseLong(request.getParameter("productId"));
            String addToCartProductDate = commUtil.getCurrentDateTime();
            cartId = prodDelegate.getCartId(userId,0L);
            prodBean = prodDelegate.getProduct(productId);
            productPrice = Long.parseLong(prodBean.getProductPrice());

            Pattern numericExp = Pattern.compile("/^[0-9]+$/");
            Matcher matchAddToQty = numericExp.matcher(addToCartQty.toString());

            if (addToCartQty.equalsIgnoreCase("")) {
                errors.add("errAddToCart", new ActionMessage("errors.addtocart.required"));
            } else if (matchAddToQty.find()) {
                errors.add("errMobileNo", new ActionMessage("errors.addtocart.invalid"));
            } else if (Integer.parseInt(addToCartQty) <= 0) {
                errors.add("errMobileNo", new ActionMessage("errors.addtocart.invalid"));
            } else if (cartId == 0) {

                cartProductCost = Long.parseLong(addToCartQty) * productPrice;
                cartCost = cartProductCost;
                cartId = prodUtil.addToCart(cartId, productId, addToCartQty, userId, addToCartProductDate, cartProductCost, cartCost);
                loginSession.setAttribute("userCartId", cartId);
            } else {
                loginSession.setAttribute("userCartId", cartId);
                ProductBean[] prodCartList = prodDelegate.getAllCartProduct(cartId);

                if (prodCartList != null) {
                    for (int i = 0; i <= prodCartList.length - 1; i++) {
                        if (prodCartList[i].getProductId() == productId) {
                            isProductExist = true;
                            temp = i;
                        }
                    }
                    if (isProductExist == true) {
                        addToCartQty = String.valueOf(Integer.parseInt(prodCartList[temp].getAddToCartQty()) + Integer.parseInt(addToCartQty));
                        cartProductCost = Long.parseLong(addToCartQty) * productPrice;
                        for (int j = 0; j <= prodCartList.length - 1; j++) {
                            cartTotal = Long.parseLong(prodCartList[j].getProductSubTotal()) + cartTotal;
                        }
                        cartCost = cartTotal + cartCost + cartProductCost;
                        boolean isCartProductUpdated = prodUtil.updateCartProduct(cartId, productId, addToCartQty, addToCartProductDate, cartProductCost, cartCost);
                    } else {
                        cartProductCost = (Long.parseLong(addToCartQty) * productPrice);
                        for (int j = 0; j <= prodCartList.length - 1; j++) {
                            cartTotal = Long.parseLong(prodCartList[j].getProductSubTotal()) + cartTotal;
                        }
                        cartCost = cartTotal + cartCost + cartProductCost;
                        cartProductId = prodUtil.addProductToCart(cartId, productId, addToCartQty, userId, addToCartProductDate, cartProductCost, cartCost);
                    }
                }
            }
            saveErrors(request, errors);
            if (errors.isEmpty()) {
                SUCCESS = "cartsuccess";
            } else {
                SUCCESS = "addtocartfailure";
            }
        } catch (Exception ex) {
            SUCCESS = "addtocartfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showCart(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        errors = new ActionErrors();
        prodUtil = new ProductUtil();
        HttpSession loginSession = request.getSession(true);
        Long cartTotal = 0L;
        try {
            commUtil.getTopRightListMap(request);
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());

            Long cartId = prodDelegate.getCartId(userId,0L);
            ProductBean[] prodCartList = prodDelegate.getAllCartProduct(cartId);
            if (prodCartList != null) {
                for (int i = 0; i <= prodCartList.length - 1; i++) {
                    cartTotal = Long.parseLong(prodCartList[i].getProductSubTotal()) + cartTotal;
                }
                request.setAttribute("cartId", cartId);
                request.setAttribute("productCartList", prodCartList);
                request.setAttribute("cartTotal", cartTotal);
            }
            SUCCESS = "cartshow";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward updateCartProductQty(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        errors = new ActionErrors();
        prodUtil = new ProductUtil();
        String cartProductQty = "";
        try {
            commUtil.getTopRightListMap(request);
            Long cartProductId = Long.parseLong(request.getParameter("cartProductId"));
            cartProductQty = request.getParameter("cartProductQty");
            if(cartProductQty.equalsIgnoreCase("") || cartProductQty == null || Integer.parseInt(cartProductQty) <= 0){
                cartProductQty = "1";
            }
            boolean isCartProductQtyUpdated = prodUtil.updateCartProductQty(cartProductId, cartProductQty);

            SUCCESS = "updatecpqty";

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward removeProductFromCart(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();
        HttpSession loginSession = request.getSession(true);
        Long cartTotal = 0L;
        try {
            commUtil.getTopRightListMap(request);
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            Long cartId = prodDelegate.getCartId(userId,0L);
            Long cartProductId = Long.parseLong(request.getParameter("cartProductId"));
            prodBean = prodDelegate.getCartProduct(cartProductId);
            Long cartProductSubTotal = Long.parseLong(prodBean.getProductSubTotal());
            cartTotal = Long.parseLong(prodBean.getCartCost()) - cartProductSubTotal;
            boolean isCartUpdated = prodDelegate.removeProductFromCart(cartProductId, cartId, cartTotal);
            if (isCartUpdated == true) {
                SUCCESS = "cartsuccess";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward clearCart(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        prodDelegate = new ProductDelegate();
        prodBean = new ProductBean();

        HttpSession loginSession = request.getSession(true);
        Long cartTotal = 0L;
        try {
            commUtil.getTopRightListMap(request);
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            Long cartId = Long.parseLong(request.getParameter("cartId"));
            boolean isCartRemoved = prodDelegate.clearCart(cartId);
            if (isCartRemoved == true) {
                SUCCESS = "cartsuccess";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }
}
